import jsTool
import random

size =16

def getRange(xx,nn):
    nn-=1
    l,m=xx-nn,xx+nn+1
    if l<0 : l=0
    if m>size : m = size
    #print (l,m)
    return range(l,m)

def search(color,cSpace,n=1):
    '''get a set of pic'''
    r,g,b=color
    
    #print 'search on ',r,g,b , n
    r,g,b=getRange(r/size,n),getRange(g/size,n),getRange(b/size,n)
    result=[]
    '''repeat too many times on central nodes , need to opt'''
    for rr in r :
        for gg in g :
            for bb in b :
                target=cSpace[rr][gg][bb]
                if target!={} :

                    result+=target.keys()
                    'break or not , need to investigate'
                    #break;
                #print target
    if result != [] : return result
    else:
        return search(color,cSpace,n+1)

def getPic(color,cSpace):
    result = search(color,cSpace)
    #print result

    r=random.randint(0,len(result)-1)
    #print 'random ',r, 'in ',len(result)
    #print color,result[r]
    return result[r]

if __name__=='__main__':
    cSpace = jsTool.j2o('colorSpace.json')
    getPic([100,100,100],cSpace)
    
